package com.asktgapp.user.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.adapter.BrandAdapter;
import com.asktgapp.adapter.MyBrandAdapter;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.base.CustomToolBrBaseActivity;
import com.asktgapp.base.SearchBaseActivity;
import com.asktgapp.eventbus.UsedMachineEvent;
import com.asktgapp.model.BrandVO;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.ProvinceVO;
import com.asktgapp.model.UsedMachineVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.PublishUsedMachineActivity;
import com.asktgapp.user.activity.UsedMachineDetailActivity;
import com.asktgapp.utils.CustomPopWindow;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;
import com.asktgapp.widget.WordsNavigation;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.dd.plist.NSArray;
import com.dd.plist.NSDictionary;
import com.dd.plist.PropertyListParser;
import com.umeng.socialize.UmengTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/23
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description: 二手设备点击类型后跳转的列表页
 * 修改时间 2018年7月21日18:54:57
 */

public class UsenMachineFragment extends BaseFragment {

    @InjectView(R.id.recycle)
    RefreshRecyclerView mRefreshRecyclerView;

    @InjectView(R.id.rd_type)
    RadioButton mTypeButton;
    @InjectView(R.id.rd_brand)
    RadioButton mBrandButton;
    @InjectView(R.id.rd_city)
    RadioButton mCityButton;
    @InjectView(R.id.rd_select)
    RadioButton mSelectButton;
    @InjectView(R.id.tv_no_data)
    TextView noDataTV;
    @InjectView(R.id.release)
    TextView release;
    CustomToolBrBaseActivity customToolBrBaseActivity;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private int mPage = 1;
    private CustomPopWindow mListPopWindow = null;
    private CustomPopWindow mBrandPopWindow = null;
    private CustomPopWindow mCityPopWindow = null;
    private CustomPopWindow mSelectPopWindow = null;
    private RecyclerView mProviceRecyclerView, mCityRecyclerView;
    private BaseAdapter mProviceAdapter, mCityAdapter;
    //初始化地区数据集，所有省份的列表{省份编号，省份名称，List<该省份下的城市>}
    List<ProvinceVO> provinceData = new ArrayList<>();
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();
    private List<BrandVO> list;
    private int isBusiness = 0;
    BaseAdapter mTypeAdapter;
    private String mChooseType = "";
    private String mChooseBrand = "";
    private int mChoosePro = 0;
    private int mChooseCity = 0;
    private boolean reset = true;
    private String workingHours = "";
    private String productionDate = "";
    private String tonnage = "";
    private String price = "";

    private BrandAdapter mBAdapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_used_machine, container, false);
        ButterKnife.inject(this, viewGroup);
        EventBus.getDefault().register(this);
        mChooseType = getArguments().getString("typeId");
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        setHasOptionsMenu(true);
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });

        release.setVisibility(View.GONE);
        release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), PublishUsedMachineActivity.class));
            }
        });

        mRecyclerView = mRefreshRecyclerView.getRecyclerView();


        customToolBrBaseActivity = (CustomToolBrBaseActivity) getActivity();
        customToolBrBaseActivity.setCustomBackNavigation(true);
        mTypeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(true);
                mBrandButton.setChecked(false);
                mCityButton.setChecked(false);
                mSelectButton.setChecked(false);
                showPopListView();
                hideBrand();
                hideCity();
                hideSelect();

            }
        });
        mBrandButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(false);
                mBrandButton.setChecked(true);
                mCityButton.setChecked(false);
                mSelectButton.setChecked(false);
                hidePopListView();
                showBrand();
                hideCity();
                hideSelect();
            }
        });
        mCityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(false);
                mBrandButton.setChecked(false);
                mCityButton.setChecked(true);
                mSelectButton.setChecked(false);
                hidePopListView();
                hideBrand();
                showCity();
                hideSelect();
            }
        });
        mSelectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(false);
                mBrandButton.setChecked(false);
                mCityButton.setChecked(false);
                mSelectButton.setChecked(true);
                hidePopListView();
                hideBrand();
                hideCity();
                showSelect();
            }
        });
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_used_machine, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                if (data instanceof UsedMachineVO) {
                                    UsedMachineVO bean = (UsedMachineVO) data;
                                    if (mBaseAdapter.getItemIndex(bean) == 0)
                                        holder.getView(R.id.tvLine).setVisibility(View.VISIBLE);
                                    else
                                        holder.getView(R.id.tvLine).setVisibility(View.GONE);
                                    ImageView saleState = holder.getView(R.id.iv_saled);
                                    ImageView img = holder.getView(R.id.iv_machine);
                                    ImageDisplayUtil.LoadNetImage(img, getActivity(), bean.getBanner_pic());
                                    holder.setText(R.id.tv_used_machine_name, bean.getTitle());
                                    holder.setText(R.id.detail, Utils.getDateYear(bean.getProduction_date()) +
                                            " | " + Utils.D2I(bean.getWorking_hours()) + "小时 | " + bean.getPro_name().replaceAll("省", "") + " " + bean.getCity_name().replaceAll("市", ""));
                                    DecimalFormat df = new DecimalFormat("0.00");
                                    holder.setText(R.id.tv_price, df.format(bean.getPrice()));
//                                    holder.setText(R.id.tvUnit, bean.getPrice_unit());
                                    Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                    String timeStr = Utils.getAskTime(date);
                                    holder.setText(R.id.addTime, timeStr);
                                    holder.setText(R.id.tvUnit, "万");
                                    if (bean.getState() == 0) {
                                        saleState.setVisibility(View.GONE);
                                    } else {
                                        saleState.setVisibility(View.VISIBLE);
                                    }

                                }


                            }

                            @Override
                            public void onItemClick(View view, int position) {
//                                UsedMachineVO bean = (UsedMachineVO) mBaseAdapter.getData().get(position);
//                                Intent intent = new Intent(getActivity(), UsedMachineDetailActivity.class);
//                                intent.putExtra("id", bean.getId());
//                                intent.putExtra("unit", bean.getPrice_unit());
//                                startActivity(intent);

                                UsedMachineVO bean = (UsedMachineVO) mBaseAdapter.getData().get(position);
                                Intent intent = new Intent(getActivity(), UsedMachineDetailActivity.class);
                                intent.putExtra("id", bean.getId());
                                intent.putExtra("unit", bean.getPrice_unit());
                                startActivity(intent);
                            }
                        });
                return holder;
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mBaseAdapter);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取省一级的数组
                    NSArray ary = (NSArray) PropertyListParser.parse(getActivity().getAssets().open("City.plist"));
                    for (int i = ary.count() - 1; i >= 0; i--) {
                        NSDictionary dic = (NSDictionary) ary.objectAtIndex(i);
                        ProvinceVO provinceVO = new ProvinceVO();
                        List<ProvinceVO.City> city = new ArrayList<>();
                        //循环遍历获取每个省的地区编号和名称
                        String areaid = dic.objectForKey("areaid").toJavaObject().toString();
                        String name = dic.objectForKey("areaname").toJavaObject().toString();
                        //从省一级的字典中获取该省下的城市字典，转换为数组
                        NSArray citys = (NSArray) dic.objectForKey("citys");
                        for (int j = citys.count() - 1; j >= 0; j--) {
                            //遍历数组获取每个城市的信息，由于文件中的默认顺序，为保证省会城市在前，采用倒序遍历
                            NSDictionary secDic = (NSDictionary) citys.objectAtIndex(j);
                            //获取城市的编号
                            String secAreaid = (secDic.objectForKey("areaid")).toJavaObject().toString();
                            //获取城市的名称
                            String secName = (secDic.objectForKey("areaname")).toJavaObject().toString();
                            ProvinceVO.City bean = new ProvinceVO.City();
                            bean.setAreaid(Integer.parseInt(secAreaid));
                            bean.setAreaname(secName);
                            //将新建的城市对象添加到该省份对象的城市列表中
                            city.add(bean);
                        }
                        ProvinceVO.City all = new ProvinceVO.City();
                        all.setAreaid(0);
                        all.setAreaname("全部");
                        city.add(0, all);
                        provinceVO.setAreaid(Integer.parseInt(areaid));
                        provinceVO.setAreaname(name);
                        provinceVO.setCitys(city);
                        provinceData.add(provinceVO);
                    }
                    ProvinceVO provinceVO = new ProvinceVO();
                    provinceVO.setAreaid(0);
                    provinceVO.setAreaname("全部");
                    List<ProvinceVO.City> city = new ArrayList<>();
                    ProvinceVO.City bean = new ProvinceVO.City();
                    bean.setAreaid(0);
                    bean.setAreaname("全部");
                    //将新建的城市对象添加到该省份对象的城市列表中
                    city.add(bean);
                    provinceVO.setCitys(city);
                    provinceData.add(0, provinceVO);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //优化适配器
        {
            mBAdapter = new BrandAdapter(getActivity(), new BrandAdapter.ItemCallback() {
                @Override
                public void onItemClick(String string, String id) {
                    mChooseBrand = id;
                    if (Util.isEmpty(id))
                        mBrandButton.setText("品牌");
                    else
                        mBrandButton.setText(string);
                    hideBrand();
                    mPage = 1;
                    getNetData(1);
                }

                @Override
                public void onDataSetComplete() {
                    dismissProgress();
                }

                @Override
                public void onStartSetData() {
                    showProgress(getClass().getSimpleName());
                }
            });

        }
    }


    public void showNoData() {
        noDataTV.setVisibility(View.VISIBLE);
        mRefreshRecyclerView.setVisibility(View.GONE);
    }

    public void hideNoData() {
        noDataTV.setVisibility(View.GONE);
        mRefreshRecyclerView.setVisibility(View.VISIBLE);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.finish, menu);
        menu.getItem(0).setTitle("发布");
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        startActivity(new Intent(getActivity(), SearchBaseActivity.class));
        if (checkIsLogin("登录后可体验更多内容"))
            startActivity(new Intent(getActivity(), PublishUsedMachineActivity.class));
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void loadData() {
        visibleLoading();
//        getType();
        getNetData(mPage);

    }

    private void getType() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList.clear();
                    mTypeList = response.body().getResult();
                    DeviceTypeVO bean = new DeviceTypeVO();
                    bean.setId("0");
                    bean.setName("全部");
                    mTypeList.add(0, bean);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }

    private void getNetData(final int mPage) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("isBusiness", isBusiness);
        params.put("page", mPage);
        if ((!Util.isEmpty(mChooseType)) && (!mChooseType.equals("0"))) {
            if (!Util.isEmpty(mChooseBrand)) {
                params.put("brandIds", mChooseBrand);
            } else {
                params.put("typeId", mChooseType);
            }
        }
        if (mChoosePro != 0) {
            params.put("areaId", mChoosePro);
            if (mChooseCity != 0) {
                params.put("cityId", mChooseCity);
            }
        }
        if (!Util.isEmpty(workingHours)) {
            params.put("workingHours", workingHours);
        }
        if (!Util.isEmpty(productionDate)) {
            params.put("productionDate", productionDate);
        }
        if (!Util.isEmpty(tonnage)) {
            params.put("tonnage", tonnage);
        }
        if (!Util.isEmpty(price)) {
            params.put("price", price);
        }

        Call<ApiResponseBody<List<UsedMachineVO>>> call = apiservice.findTwoHardList(params);
        call.enqueue(new Callback<ApiResponseBody<List<UsedMachineVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<UsedMachineVO>>> call, Response<ApiResponseBody<List<UsedMachineVO>>> response) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                mRefreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    List<UsedMachineVO> list = response.body().getResult();
                    if (mPage == 1) {
                        if (list.size() == 0) {
                            showNoData();
                        } else {
                            hideNoData();
                            mBaseAdapter.setData(list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    } else {
                        if (list.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }
                } else {
                    showTost(response.message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<UsedMachineVO>>> call, Throwable t) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.reset(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUsedMachineEvent(UsedMachineEvent event) {
        if (event.getType() == 100) {
//            showTost("个人", 0);
            isBusiness = 0;
            mRefreshRecyclerView.showSwipeRefresh();
        } else {
//            showTost("商家", 0);
            isBusiness = 1;
            mRefreshRecyclerView.showSwipeRefresh();
        }

    }

    private void hidePopListView() {
        if (mListPopWindow != null)
            mListPopWindow.dissmiss();
    }

    private void hideBrand() {
        if (mBrandPopWindow != null)
            mBrandPopWindow.dissmiss();
    }

    private void hideCity() {
        if (mCityPopWindow != null)
            mCityPopWindow.dissmiss();
    }

    private void hideSelect() {
        if (mSelectPopWindow != null)
            mSelectPopWindow.dissmiss();
    }


    /****************************************** 展示设备类型模块开始***********************/
    private void showPopListView() {
        if (mListPopWindow != null) {
            mListPopWindow.showAsDropDown(mTypeButton, 0, 5);
        } else {
            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.item_recyclerview, null);
            FrameLayout bg = contentView.findViewById(R.id.bg);

            //处理popWindow 显示内容
            final RecyclerView recyclerView = contentView.findViewById(R.id.recycle);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

            mTypeAdapter = new BaseAdapter(getActivity()) {
                @Override
                public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                    BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_type_choose, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            if (data instanceof DeviceTypeVO) {
                                DeviceTypeVO bean = (DeviceTypeVO) data;
                                TextView type = holder.getView(R.id.tv_type);
                                ImageView choose = holder.getView(R.id.iv_choose);
                                type.setText(bean.getName());
                                if (bean.isChoose()) {
                                    choose.setVisibility(View.VISIBLE);
                                } else {
                                    choose.setVisibility(View.GONE);
                                }
                            }

                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            DeviceTypeVO bean = (DeviceTypeVO) mTypeAdapter.getData().get(position);
                            mChooseType = bean.getId();
                            List<DeviceTypeVO> list = mTypeAdapter.getData();
                            for (int i = 0; i < list.size(); i++) {
                                DeviceTypeVO vo = list.get(i);
                                if (vo.getId() == bean.getId()) {
                                    vo.setChoose(true);
                                } else {
                                    vo.setChoose(false);
                                }
                            }
                            mTypeAdapter.setData(list);
                            recyclerView.scrollToPosition(position);
                            mListPopWindow.dissmiss();
                            mPage = 1;
                            mChooseBrand = "";
                            getNetData(mPage);
//                            getBrandLlist();
                        }
                    });
                    return holder;
                }
            };
            mTypeAdapter.setData(mTypeList);
            recyclerView.setAdapter(mTypeAdapter);


            //创建并显示popWindow
            mListPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mTypeButton.setChecked(false);
                        }
                    })
                    .setTouchable(true)
                    .setOutsideTouchable(true)
                    .create()
                    .showAsDropDown(mTypeButton, 0, 5);
            bg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListPopWindow.dissmiss();
                    mTypeButton.setChecked(false);

                }
            });
        }
    }

    private void showBrand() {
        getBrandLlist();
    }

    private void getBrandLlist() {
        if (list != null && list.size() > 0) {
            initData();
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        if (Util.isEmpty(mChooseType) || mChooseType.equals("0")) {
            showTost("请先选择设备类型", 1);
            mBrandButton.setChecked(false);
            return;
        }
        params.put("typeId", mChooseType);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<List<BrandVO>>> call = apiservice.getBrandList(params);
        call.enqueue(new Callback<ApiResponseBody<List<BrandVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<BrandVO>>> call, Response<ApiResponseBody<List<BrandVO>>> response) {
                if (response.isSuccessful()) {
                    list = response.body().getResult();
                    BrandVO brandVO = new BrandVO();
                    brandVO.setName("全部");
                    brandVO.setIsHot(1);
                    brandVO.setTypeId(0);
                    brandVO.setId(" ");
                    list.add(0, brandVO);
                    initData();
                } else {
                    dismissProgress();
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<BrandVO>>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);

            }
        });

    }

    /****************************************** 展示品牌选择模块开始***********************/
    /**
     * 初始化联系人列表信息
     */
    private void initData() {
        if (mBrandPopWindow != null) {
            mBrandPopWindow.showAsDropDown(mBrandButton, 0, 5);
            if (mBAdapter.getCount() < 1) {
                mBAdapter.setData(list);
            }
            return;
        }

//        //对集合排序
//        Collections.sort(list, new Comparator<BrandVO>() {
//            @Override
//            public int compare(BrandVO lhs, BrandVO rhs) {
//                //根据拼音进行排序
//                return lhs.getPinyin().compareTo(rhs.getPinyin());
//            }
//        });
        final ListView mBrandListView;
//        final MyBrandAdapter mBrandAdapter;
        final WordsNavigation mBrandWordNavigation;

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_choose_brand, null);
        mBrandListView = contentView.findViewById(R.id.list);
        mBrandWordNavigation = contentView.findViewById(R.id.words);
//        mBrandAdapter = new MyBrandAdapter(getActivity(), list, new MyBrandAdapter.ItemCallback() {
//            @Override
//            public void onItemClick(String string, String id) {
//                mChooseBrand = id;
////                showTost(string, 0);
//                hideBrand();
//                mPage = 1;
//                getNetData(1);
//
//            }
//        });
        mBrandWordNavigation.setOnWordsChangeListener(new WordsNavigation.onWordsChangeListener() {
            @Override
            public void wordsChange(String words) {
                if (words.equals("#")) {
                    words = "热门品牌";
                }
//                for (int i = 0; i < mBrandAdapter.getData().size(); i++) {
//                    if (mBrandAdapter.getData().get(i).getHeadChar().equals(words)) {
//                        mBrandListView.setSelection(i);
//                        return;
//                    }
//                    String headerWord = mBrandAdapter.getData().get(i).getHeadChar().toUpperCase();
//                    //将手指按下的字母与列表中相同字母开头的项找出来
//                    if (words.equals(headerWord)) {
//                        //将列表选中哪一个
//                        mBrandListView.setSelection(i);
//                        //找到开头的一个即可
//                        return;
//                    }
//                }
                for (int i = 0; i < mBAdapter.getData().size(); i++) {
                    if (mBAdapter.getData().get(i).getHeadChar().equals(words)) {
                        mBrandListView.setSelection(i);
                        return;
                    }
                    String headerWord = mBAdapter.getData().get(i).getHeadChar().toUpperCase();
                    //将手指按下的字母与列表中相同字母开头的项找出来
                    if (words.equals(headerWord)) {
                        //将列表选中哪一个
                        mBrandListView.setSelection(i);
                        //找到开头的一个即可
                        return;
                    }
                }
            }
        });


//        mBrandListView.setAdapter(mBrandAdapter);
        mBrandListView.setAdapter(mBAdapter);
        mBrandListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //当滑动列表的时候，更新右侧字母列表的选中状态
//                if (mBrandAdapter.getData().get(firstVisibleItem).getHeadChar().equals("热门品牌")) {
//                    mBrandWordNavigation.setTouchIndex("#");
//                } else {
//                    mBrandWordNavigation.setTouchIndex(mBrandAdapter.getData().get(firstVisibleItem).getHeadChar().toUpperCase());
//                }
                if (mBAdapter.getData().size() > 0) {
                    if (mBAdapter.getData().get(firstVisibleItem).getHeadChar().equals("热门品牌")) {
                        mBrandWordNavigation.setTouchIndex("#");
                    } else {
                        mBrandWordNavigation.setTouchIndex(mBAdapter.getData().get(firstVisibleItem).getHeadChar().toUpperCase());
                    }
                }
            }
        });
        //创建并显示popWindow
        mBrandPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        mBrandButton.setChecked(false);
//
                    }
                })
                .setTouchable(true)
                .setOutsideTouchable(true)
                .create()
                .showAsDropDown(mBrandButton, 0, 5);
        mBAdapter.setData(list);
//        dismissProgress();

    }


    int mChoosePositon = 0;
    private String cityText = "全部";

    /****************************************** 展示城市选择模块开始***********************/
    private void showCity() {
        mChoosePositon = 0;
        if (mCityPopWindow != null) {
            mCityAdapter.setData(provinceData.get(mChoosePositon).getCitys());
            mCityPopWindow.showAsDropDown(mCityButton, 0, 5);
        } else {
            //显示地区POp

            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_choose_city, null);
            mProviceRecyclerView = contentView.findViewById(R.id.left_recycler);
            mCityRecyclerView = contentView.findViewById(R.id.right_recycler);
            mProviceAdapter = new BaseAdapter(getActivity()) {
                @Override
                public BaseViewHolder getViewHolder(ViewGroup parent, final int viewType) {
                    BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_province, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            if (data instanceof ProvinceVO) {
                                TextView province = holder.getView(R.id.textView);
                                ProvinceVO provinceVO = (ProvinceVO) data;
                                province.setText(provinceVO.getAreaname());
                                if (viewType == 1) {
                                    province.setBackgroundColor(Color.WHITE);
                                } else {
                                    province.setBackgroundColor(Color.parseColor("#e0e0e0"));
                                }
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            mChoosePositon = position;
                            mProviceAdapter.notifyDataSetChanged();
                            mProviceRecyclerView.smoothScrollToPosition(mChoosePositon);
                            ProvinceVO provinceVO = (ProvinceVO) mProviceAdapter.getData().get(position);
                            mCityAdapter.setData(provinceVO.getCitys());
                            mCityRecyclerView.smoothScrollToPosition(0);
                            mChoosePro = provinceVO.getAreaid();
                            cityText = provinceVO.getAreaname();
                        }
                    });
                    return holder;
                }

                @Override
                public int getItemViewType(int position) {
                    if (position == mChoosePositon) {
                        return 1;
                    } else return 0;
                }
            };
            mCityAdapter = new BaseAdapter(getActivity()) {
                @Override
                public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                    BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_city, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            if (data instanceof ProvinceVO.City) {
                                TextView city = holder.getView(R.id.city);
                                ProvinceVO.City bean = (ProvinceVO.City) data;
                                city.setText(bean.getAreaname());
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            ProvinceVO.City city = (ProvinceVO.City) mCityAdapter.getData().get(position);
//                            showTost("名称：" + city.getAreaname() + "  编号：" + city.getAreaid(), 1);
                            if (city.getAreaid() == 110100) {
                                mChoosePro = 110000;
                            }
                            if (mChoosePositon == 0) {
                                mChoosePro = 0;
                            }
                            mChooseCity = city.getAreaid();
                            mPage = 1;
                            hideCity();
                            if (cityText.equals("全部")) {
                                mCityButton.setText("地区");
                            } else {
                                if (!city.getAreaname().equals("全部")) {
                                    mCityButton.setText(city.getAreaname());
                                } else {
                                    mCityButton.setText(cityText);
                                }
                            }
                            cityText = "全部";
                            getNetData(mPage);
                        }
                    });
                    return holder;
                }
            };
            mCityRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            mProviceRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            mCityRecyclerView.setAdapter(mCityAdapter);
            mProviceRecyclerView.setAdapter(mProviceAdapter);
            mProviceAdapter.setData(provinceData);
            mCityAdapter.setData(provinceData.get(0).getCitys());

            //创建并显示popWindow
            mCityPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mCityButton.setChecked(false);
                        }
                    })
                    .setTouchable(true)
                    .setOutsideTouchable(true)
                    .create()
                    .showAsDropDown(mCityButton, 0, 5);
        }

    }

    /****************************************** 展示城市选择模块结束***********************/

    CheckBox[] Work = new CheckBox[5];
    CheckBox[] Year = new CheckBox[5];
    CheckBox[] Weight = new CheckBox[6];
    CheckBox[] Price = new CheckBox[9];

    public String getWrokHours() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Work.length; i++) {
            if (Work[i].isChecked()) {
                sb.append(i + ",");

            }
        }
        if (Util.isEmpty(sb.toString())) {
            return "";
        } else
            return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public String getYear() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Year.length; i++) {
            if (Year[i].isChecked()) {
                sb.append(i + ",");
            }
        }
        if (Util.isEmpty(sb.toString())) {
            return "";
        } else
            return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public String getWeight() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Weight.length; i++) {
            if (Weight[i].isChecked()) {
                sb.append(i + ",");
            }
        }
        if (Util.isEmpty(sb.toString())) {
            return "";
        } else
            return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public String getPrice() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Price.length; i++) {
            if (Price[i].isChecked()) {
                sb.append(i + ",");
            }
        }
        if (Util.isEmpty(sb.toString())) {
            return "";
        } else
            return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public void showSelect() {
        if (mSelectPopWindow != null) {
            mSelectPopWindow.showAsDropDown(mCityButton, 0, 20);
        } else {
            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.frgment_select, null);
            Work[0] = contentView.findViewById(R.id.cb_time1);
            Work[1] = contentView.findViewById(R.id.cb_time2);
            Work[2] = contentView.findViewById(R.id.cb_time3);
            Work[3] = contentView.findViewById(R.id.cb_time4);
            Work[4] = contentView.findViewById(R.id.cb_time5);
            Year[0] = contentView.findViewById(R.id.cb_year1);
            Year[1] = contentView.findViewById(R.id.cb_year2);
            Year[2] = contentView.findViewById(R.id.cb_year3);
            Year[3] = contentView.findViewById(R.id.cb_year4);
            Year[4] = contentView.findViewById(R.id.cb_year5);
            Weight[0] = contentView.findViewById(R.id.cb_weight1);
            Weight[1] = contentView.findViewById(R.id.cb_weight2);
            Weight[2] = contentView.findViewById(R.id.cb_weight3);
            Weight[3] = contentView.findViewById(R.id.cb_weight4);
            Weight[4] = contentView.findViewById(R.id.cb_weight5);
            Weight[5] = contentView.findViewById(R.id.cb_weight6);
            Price[0] = contentView.findViewById(R.id.cb_price1);
            Price[1] = contentView.findViewById(R.id.cb_price2);
            Price[2] = contentView.findViewById(R.id.cb_price3);
            Price[3] = contentView.findViewById(R.id.cb_price4);
            Price[4] = contentView.findViewById(R.id.cb_price5);
            Price[5] = contentView.findViewById(R.id.cb_price6);
            Price[6] = contentView.findViewById(R.id.cb_price7);
            Price[7] = contentView.findViewById(R.id.cb_price8);
            Price[8] = contentView.findViewById(R.id.cb_price9);
            TextView sure = contentView.findViewById(R.id.tv_sure);

            mSelectPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mSelectButton.setChecked(false);
                        }
                    })
                    .setTouchable(true)
                    .setOutsideTouchable(true)
                    .create()
                    .showAsDropDown(mSelectButton, 0, 5);
            sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    workingHours = getWrokHours();
                    productionDate = getYear();
                    tonnage = getWeight();
                    price = getPrice();
                    hideSelect();
                    mSelectButton.setChecked(false);
                    mPage = 1;
                    getNetData(mPage);

                }
            });
            TextView reset = contentView.findViewById(R.id.tv_reset);
            reset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    doRest();
                }
            });
        }
    }

    private void doRest() {
        if (Work != null) {
            for (int i = 0; i < Work.length; i++) {
                Work[i].setChecked(false);
            }
        }
        if (Year != null) {
            for (int i = 0; i < Year.length; i++) {
                Year[i].setChecked(false);
            }
        }
        if (Weight != null) {
            for (int i = 0; i < Weight.length; i++) {
                Weight[i].setChecked(false);
            }
        }
        if (Price != null) {
            for (int i = 0; i < Price.length; i++) {
                Price[i].setChecked(false);
            }
        }
    }

}
